package org.diffshop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.diffshop.common.constant.ProductConstant;
import org.diffshop.common.enums.BizCodeEnum;
import org.diffshop.common.exception.RRException;
import org.diffshop.common.to.SkuFullReductionTO;
import org.diffshop.common.utils.PageUtils;
import org.diffshop.common.utils.Query;
import org.diffshop.common.utils.R;
import org.diffshop.product.dao.PmsSkuInfoDao;
import org.diffshop.product.entity.PmsSkuImagesEntity;
import org.diffshop.product.entity.PmsSkuInfoEntity;
import org.diffshop.product.entity.PmsSkuSaleAttrValueEntity;
import org.diffshop.product.feign.CouponFeignService;
import org.diffshop.product.service.PmsAttrService;
import org.diffshop.product.service.PmsSkuImagesService;
import org.diffshop.product.service.PmsSkuInfoService;
import org.diffshop.product.service.PmsSkuSaleAttrValueService;
import org.diffshop.product.vo.Images;
import org.diffshop.product.vo.Skus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service("pmsSkuInfoService")
public class PmsSkuInfoServiceImpl extends ServiceImpl<PmsSkuInfoDao, PmsSkuInfoEntity> implements PmsSkuInfoService {
    @Autowired
    private PmsAttrService attrService;
    @Autowired
    private PmsSkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private PmsSkuImagesService skuImagesService;
    @Autowired
    private CouponFeignService couponFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<PmsSkuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)){
            queryWrapper.and(wrapper -> {
                wrapper.eq(PmsSkuInfoEntity::getSkuId, key).or().like(PmsSkuInfoEntity::getSkuName, key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equals(catelogId)){
            queryWrapper.eq(PmsSkuInfoEntity::getCatalogId, catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(brandId) && !"0".equals(brandId)){
            queryWrapper.eq(PmsSkuInfoEntity::getBrandId, brandId);
        }

        String min = (String) params.get("min");
        if (StringUtils.isNotEmpty(min)){
            try{
                BigDecimal minD = new BigDecimal(min);
                if (minD.compareTo(BigDecimal.ZERO) == 1){
                    queryWrapper.ge(PmsSkuInfoEntity::getPrice, minD);
                }
            }catch (Exception e){
                log.error(this.getClass() + "--转换数字失败，{}", e.getMessage());
            }
        }

        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(max)){
            try{
                BigDecimal maxD = new BigDecimal(max);
                if (maxD.compareTo(BigDecimal.ZERO) == 1){
                    queryWrapper.le(PmsSkuInfoEntity::getPrice, maxD);
                }
            }catch (Exception e){
                log.error(this.getClass() + "--转换数字失败，{}", e.getMessage());
            }
        }

        IPage<PmsSkuInfoEntity> page = this.page(
                new Query<PmsSkuInfoEntity>().getPage(params), queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 批量保存sku信息
     *
     * @param catalogId
     * @param brandId
     * @param skus
     */
    public void saveDetailBatch(Long spuId, Long catalogId, Long brandId, List<Skus> skus) {
        if (skus == null || skus.size() == 0) {
            return;
        }

        // 1 sku视图对象转为sku实体并保存
        skus.stream().forEach(sku -> {
            PmsSkuInfoEntity skuInfoEntity = new PmsSkuInfoEntity();
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoEntity.setSpuId(spuId);
            skuInfoEntity.setCatalogId(catalogId);
            skuInfoEntity.setBrandId(brandId);
            skuInfoEntity.setSaleCount(0L);
            String defaultImage = "";
            for (Images image : sku.getImages()) {
                if (image.getDefaultImg() == ProductConstant.imageEnum.DEFAULT_IMAGE.getCode()){
                    defaultImage = image.getImgUrl();
                    break;
                }
            }
            skuInfoEntity.setSkuDefaultImg(defaultImage);
            baseMapper.insert(skuInfoEntity);

            Long skuId = skuInfoEntity.getSkuId();

            // 2 批量保存销售属性实体
            if (sku.getAttr() != null && sku.getAttr().size() > 0) {
                List<PmsSkuSaleAttrValueEntity> attrValueEntities = sku.getAttr().stream().map(attr -> {
                    PmsSkuSaleAttrValueEntity saleAttrValueEntity = new PmsSkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, saleAttrValueEntity);
                    saleAttrValueEntity.setSkuId(skuId);
                    return saleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValueEntities);
            }

            // 3 批量保存图片
            if (sku.getImages() != null && sku.getImages().size() > 0) {
                List<PmsSkuImagesEntity> skuImageEntities = sku.getImages().stream().map(skuImage -> {
                    PmsSkuImagesEntity skuImagesEntity = new PmsSkuImagesEntity();
                    BeanUtils.copyProperties(skuImage, skuImagesEntity);
                    skuImagesEntity.setSkuId(skuId);
                    return skuImagesEntity;
                }).filter(skuImage -> {
                    // 没有img_url的不保存
                    return StringUtils.isNotEmpty(skuImage.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImageEntities);
            }

            // 保存当前sku的优惠信息 如：满减优惠、满折优惠、会员等级优惠
            SkuFullReductionTO skuFullReductionTO = new SkuFullReductionTO();
            BeanUtils.copyProperties(sku, skuFullReductionTO);
            skuFullReductionTO.setSkuId(skuId);
            R response = couponFeignService.saveSkuFullReduction(skuFullReductionTO);
            if (response.getCode() != 0){
                log.error("保存优惠信息失败！" + response.getMsg());
                throw new RRException(BizCodeEnum.UNKNOWN_EXCEPTION.getMsg(), BizCodeEnum.UNKNOWN_EXCEPTION.getCode());
            }
            // 如果保存优惠的服务挂了？如果连接超时呢？
//            int i = 1 / 0;
        });
    }

}
